package com.taotao.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.common.utils.JsonUtils;
import com.taotao.utils.FastDFSClient;

/**
 * 图片上传的控制器
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/pic")
public class PictureController {

	@Value(value="${IMAGE_SERVER_URL}")
	public String IMAGE_SERVER_URL;
	
	@RequestMapping(value="/upload",produces=MediaType.TEXT_PLAIN_VALUE+";charset=UTF-8")
	@ResponseBody
	public String uploadPic(MultipartFile uploadFile){
		//定义返回浏览器的数据封装
		Map<String, Object> map = new HashMap<>();
		try {
			//获取所有的上传文件
			byte[] fileContent = uploadFile.getBytes();
			//获取上传文件的名称
			String filename = uploadFile.getOriginalFilename();
			//获取扩展名
			String extName = filename.substring(filename.lastIndexOf(".")+1);
			//使用工具类fastdfsclient上传图片  获取对象
			FastDFSClient fastDFSClient = new FastDFSClient("classpath:resource/fdfs_client.conf");
			//上传图片   返回url
			String url = fastDFSClient.uploadFile(fileContent, extName);
			//封装数据  上传成功
			map.put("error", 0);
			map.put("url", IMAGE_SERVER_URL+url);
		} catch (Exception e) {
			//上传失败
			map.put("error", 1);
			map.put("message", "文件上传失败!");
			e.printStackTrace();
		}
		//使用jsonutils工具类  返回json字符串
		return JsonUtils.objectToJson(map);
	}
	
}
